package com.pgy.general.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.pgy.general.annotation.PassToken;
import com.pgy.general.entity.User;
import com.pgy.general.exceptions.LoginRuntimeException;
import com.pgy.general.service.IUserService;
import com.pgy.general.util.IPUtil;
import com.pgy.general.util.TokenUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
 * @Auther:superChao
 * @Date: 2021/01/26/15:58
 * @Version:2.0.0
 * 身份验证拦截器
*/

public class AuthenticationInterceptor implements HandlerInterceptor {
    //利用logback将信息计入日志
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);

    @Autowired
    private IUserService iUserService;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();

        //检查是否有passtoken注解，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        // 执行认证
        if (token == null) {
            throw new LoginRuntimeException("无令牌，请重新登录");
        }
        // 获取 token 中的 user id
        String userId;
        String realIp= IPUtil.getRemortIP(httpServletRequest);
        try {
            Claims claims1 = Jwts.parser()
                    .setSigningKey("a1g2y47dg3dj59fjhhsd7cnewy73j")
                    .parseClaimsJws(token)
                    .getBody();
            userId=claims1.getId();
            Object remortIp = claims1.get("remortIp");
            Date d1 = claims1.getIssuedAt();
            Date d2 = claims1.getExpiration();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            logger.info("创建时间："+sdf.format(d1)+";  过期时间:"+sdf.format(d2)+";   当前时间"+sdf.format(new Date()));
            if (!realIp.equals(remortIp)){
                throw new LoginRuntimeException("出现网络变更，请重新登录！");
            }
            System.out.println("创建时间："+sdf.format(d1)+";  过期时间:"+sdf.format(d2)+";   当前时间"+sdf.format(new Date()));
        } catch (JWTDecodeException j) {
            //无token
            throw new LoginRuntimeException("操作失败，请重新登录");
        }catch (ExpiredJwtException ej){
            logger.error("过期账号信息："+"/n请求token:"+token);
            throw new LoginRuntimeException("登录已过期，请重新登录！");
        }catch (Exception var20) {
            throw new LoginRuntimeException("令牌错误，请重新登录！");
        }
        User user = iUserService.queryById(userId);
        logger.error("账号信息："+user.getName()+"、"+user.getUsername());
        if (user == null) {
            throw new LoginRuntimeException("用户不存在，请重新登录！");
        }
        // 验证 token
          //      JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            //jwtVerifier.verify(token);
            TokenUtil.verifyToken(token);
        } catch (JWTVerificationException e) {
            throw new LoginRuntimeException("令牌验证错误！");
        }catch (Exception e){
            throw new LoginRuntimeException("登录异常！");
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}
